﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using GroundWater.Data;
using GroundWater.BusinessActions;

using MonitoringTable = GroundWater.Data.MonitoringDataSet.MonitoringDataTable;
using MonitoringRow = GroundWater.Data.MonitoringDataSet.MonitoringRow;

using WellTable = GroundWater.Data.InfoDataSet.WellsDataTable;
using WellRow = GroundWater.Data.InfoDataSet.WellsRow;


namespace GroundWater.waterlevel
{
    public partial class monitoringquery : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "水位数据查询");
            if (!this.IsPostBack)
            {
                txtStartDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                txtEndDate.Value = DateTime.Now.ToString("yyyy-MM-dd");

                WellTable wells = Well.GetAll(false, true);

                if (wells == null || wells.Count == 0)
                {
                    gvMonitoring.Visible = false;
                    RegisterClientScript("alert('还没有水井信息，请先输入');", lblJavaScript);
                }
            }
            //Monitoring.GetPaged(1, 1);
        }

        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }
        }

        protected void odsMonitoring_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {

        }

        protected void gvMonitoring_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            //string wellCode = drpWell.SelectedValue;
            //string startDate = txtStartDate.Value;
            //string endDate = txtEndDate.Value;

            //updPanel.Update();
            gvMonitoring.PageIndex = 0;
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (drpWell.SelectedItem != null)
            {
                MonitoringTable dt = Monitoring.FetchPaged(drpWell.SelectedItem.Value, txtStartDate.Value, txtEndDate.Value, "", 1000000, 0);
                ExportToExcel(drpWell.SelectedItem.Text + ".xls", dt, gvMonitoring);
            }
        }



        public void ExportToExcel(string fileName, DataTable dt, GridView gv)
        {
            this.Page.Response.Clear();
            this.Page.Response.Buffer = true;
            this.Page.Response.AddHeader("Content-type", "application/x-msdownload");
            this.Page.Response.ContentType = "application/vnd.ms-excel";
            this.Page.Response.Charset = "utf-8";
            this.Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            this.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
            this.EnableViewState = false;

            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            GridView grid = new GridView();

            grid.RowDataBound += new GridViewRowEventHandler(gvExport_RowDataBound);
            grid.DataSource = dt;
            grid.AutoGenerateColumns = false;
            grid.Columns.Clear();
            foreach (DataControlField col in gv.Columns)
            {
                if (col is ButtonField || col is CommandField)
                {
                    continue;
                }
                if (col is BoundField || col is TemplateField || col is CheckBoxField)
                {
                    grid.Columns.Add(col);
                }
                if (col is HyperLinkField)
                {
                    BoundField field = new BoundField();
                    field.DataField = ((HyperLinkField)col).DataTextField;
                    field.HeaderText = col.HeaderText;
                    grid.Columns.Add(field);
                }
            }

            grid.DataBind();
            grid.RenderControl(htw);

            this.Page.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            this.Page.Response.Write(@"<style> .text { mso-number-format:\@; } </style> "); ;
            //string fileName = HttpUtility.UrlEncode(ExcelFileName + ".xls", Encoding.GetEncoding("GB2312"));
            //HttpContext.Current.Response.AddHeader("content-disposition","attachment;filename=" + fileName);
            this.Page.Response.Write(sw.ToString());
            this.Page.Response.End();
        }

        protected void gvExport_RowDataBound(object sender, GridViewRowEventArgs args)
        {
            if (args.Row.RowType == DataControlRowType.DataRow)
            {
                args.Row.Cells[4].Attributes.Add("class", "text");
            }
        }

        protected void drpWell_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ods_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.InputParameters["id"] = e.InputParameters["Code"];
            e.InputParameters.Remove("Code");
        }

        //protected void btnEdit_Click(object sender, EventArgs e)
        //{
        //    ClearFields();
        //    GridViewRow row = ((LinkButton)sender).Parent.Parent as GridViewRow;

        //    string wellCode = this.gvMonitoring.DataKeys[row.RowIndex].Value.ToString();
        //    string monitorTime = this.gvMonitoring.DataKeys[row.RowIndex].Values[1].ToString();
        //    SetFields(wellCode, DateTime.Parse(monitorTime));

        //    updPnl.Update();
        //    txtCode.Enabled = false;

        //    mdlPopup.Show();
        //}

        //private void SetFields(string wellCode, DateTime monitorTime)
        //{
        //    if (!string.IsNullOrEmpty(wellCode))
        //    {
        //        MonitoringRow row = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, monitorTime);
        //        txtCode.Text = row.WellCode;
        //        txtName.Text = row.WellName;
        //        txtMonitorTime.Text = row.MonitorTime.ToString("yyyy-MM-dd HH:mm:ss");
        //        txtWaterlevel.Text = row.Waterlevel.ToString();
        //        if (!row.IsCellVoltageNull())
        //        {
        //            txtCellVoltage.Text = row.CellVoltage;
        //        }
        //        if (!row.IsFlowRateNull())
        //        {
        //            txtFlowRate.Text = row.FlowRate.ToString();
        //        }
                
        //        if (!row.IsHydraulicPressureNull())
        //        {
        //            txtHydraulicPressure.Text = row.HydraulicPressure.ToString();
        //        }
                
        //        if (!row.IsOriginalWaterLevelNull())
        //        {
        //            txtOriginalWaterLevel.Text = row.OriginalWaterLevel;
        //        }
        //        if (!row.IsWaterQualityNull())
        //        {
        //            txtWaterQuality.Text = row.WaterQuality;
        //        }
        //        if (!row.IsSectionPlaneNull())
        //        {
        //            txtSectionPlane.Text = row.SectionPlane;
        //        }
        //        if (!row.IsSIMCardNull())
        //        {
        //            txtSIMCard.Text = row.SIMCard;
        //        }
                
        //        if (!row.IsSIMCardNull())
        //        {
        //            txtBTUAddress.Text = row.BTUAddress;
        //        }


        //        this.ViewState["WellCode"] = wellCode;
        //        this.ViewState["MonitorTime"] = monitorTime;
        //    }
        //}

        //protected void btnOK_Click(object sender, EventArgs e)
        //{
        //    if (txtCode.Text.Trim().Length == 0 || txtName.Text.Length == 0) return;
        //    string wellCode = this.ViewState["WellCode"] as String;
        //    DateTime monitorTime = DateTime.Parse("1900-01-01");
        //    if(this.ViewState["MonitorTime"] != null)
        //    {
        //        monitorTime = (DateTime)this.ViewState["MonitorTime"];
        //    }


        //    MonitoringDataSet s = GetFields(wellCode, monitorTime);
        //    if (s == null)
        //    {
        //        //
        //        lblJavaScript.Text = "<script type=\"text/javascript\">alert('已存在代码为" + txtCode.Text.Trim() + " 的水源地。');</script>";
        //    }

        //    GroundWater.BusinessActions.Monitoring.Update(s, false, true, new string[] { s.Monitoring.TableName });

        //    gvMonitoring.DataBind();

        //    updPanel.Update();
        //    this.ViewState.Remove("WellCode");
        //    this.ViewState.Remove("MonitorTime");

        //    ClearFields();
        //}

        //private void ClearFields()
        //{
        //    txtCode.Text = "";
        //    txtName.Text = "";
        //    txtMonitorTime.Text = "";
        //    txtWaterlevel.Text = "";
        //    txtCellVoltage.Text = "";
        //    txtFlowRate.Text = "";
        //    txtHydraulicPressure.Text = "";
        //    txtOriginalWaterLevel.Text = "";
        //    txtWaterQuality.Text = "";
        //    txtSectionPlane.Text = "";
        //    txtSIMCard.Text = "";
        //    txtBTUAddress.Text = "";
        //    //txtYearlyQuality.Text = "";
        //    //txtDailyQuality.Text = "";
        //    //txtAdministrationAgency.Text = "";
        //    //txtAdministration.Text = "";
            
        //}

        //private MonitoringDataSet GetFields(string wellCode, DateTime monitorTime)
        //{
        //    MonitoringRow src = null;

        //    if (String.IsNullOrEmpty(wellCode))
        //    {
        //        MonitoringRow row = GroundWater.BusinessActions.Monitoring.FetchById( wellCode, monitorTime);
        //        if (row != null)
        //        {
        //            return null;
        //        }

        //        src = (new MonitoringDataSet()).Monitoring.NewMonitoringRow();
        //        src.WellCode = "";
        //        src.WellName = "";
        //        src.BTUAddress = "";
        //        src.CellVoltage = "";
        //        src.FlowRate = 0m;
        //        src.HydraulicPressure = 0m;
        //        src.MonitorTime = DateTime.Parse("1900-01-01");
        //        src.OriginalWaterLevel = "";
        //        src.SectionPlane = "";
        //        src.SIMCard = "";
        //        src.Waterlevel = 0m;
        //        src.WaterQuality = "";
        //    }
        //    else
        //    {
        //        // update
        //        src = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, monitorTime);
        //    }
        //    src.WellCode = txtCode.Text;
        //    src.WellName = txtName.Text;
        //    src.BTUAddress = txtBTUAddress.Text;
        //    src.CellVoltage = txtCellVoltage.Text;
        //    src.OriginalWaterLevel = txtOriginalWaterLevel.Text;
        //    src.SectionPlane = txtSectionPlane.Text;
        //    src.SIMCard = txtSIMCard.Text;
        //    src.MonitorTime = DateTime.Parse(txtMonitorTime.Text);
        //    src.FlowRate = Convert.ToDecimal(txtFlowRate.Text);
        //    src.HydraulicPressure = Convert.ToDecimal(txtHydraulicPressure.Text);
        //    src.Waterlevel = Convert.ToDecimal(txtWaterlevel.Text);
        //    src.WaterQuality = txtWaterQuality.Text;

        //    if (String.IsNullOrEmpty(wellCode))
        //    {
        //        src.Table.Rows.Add(src);
        //    }
        //    else
        //    {

        //    }

        //    return src.Table.DataSet as MonitoringDataSet;
        //}

        //protected void btnAdd_Click(object sender, EventArgs e)
        //{
        //    txtCode.Enabled = true;

        //    ClearFields();
        //    mdlPopup.Show();
        //}

        protected void drpWell_DataBound(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            if (!String.IsNullOrEmpty(id))
            {
                //SetFields(id);
                foreach (ListItem item in drpWell.Items)
                {
                    if (item.Value == id)
                    {
                        item.Selected = true;
                        break;
                    }
                }
                
            }
        }

    }
}
